﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;
using DevExpress.XtraGrid;

namespace ReportGenerators.HanSuDung
{
    public partial class FrmQuanLyHanSuDung : BasicForms.FrmSupportPrintableComponents
    {
        public FrmQuanLyHanSuDung()
        {
            InitializeComponent();
        }

        StyleFormatCondition _StyleConditionGioiHanSoNgayConHang = new DevExpress.XtraGrid.StyleFormatCondition();
        dsHanSuDung dsHanSuDung = new dsHanSuDung();

        private void FrmQuanLyHanSuDung_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbNhomVatTuHangHoa.DataSource = DanhMucNhomVatTuHangHoa.Instance.DataView;
                cmbNhomVatTuHangHoa.DisplayColumn = "Ten";
                cmbNhomVatTuHangHoa.ValueColumn = "ID";
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ma", "Mã");
                cmbNhomVatTuHangHoa.AddVisibleColumn("Ten", "Tên");

                cmbKyBaoCao.SelectedIndex = 19;
                txtGioiHanTren.Text = "60";

                dsHanSuDung.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDungCoCotChoose());
                gridControlDsVatTuHangHoa.DataSource = dsHanSuDung.VatTuHangHoa;
                gridcontrolMain.DataSource = dsHanSuDung.HanSuDungDetail;

                _StyleConditionGioiHanSoNgayConHang.Appearance.BackColor = Color.Pink;
                _StyleConditionGioiHanSoNgayConHang.Appearance.Options.UseBackColor = true;
                _StyleConditionGioiHanSoNgayConHang.Column = gridViewMain.Columns["NgayConLai"];
                _StyleConditionGioiHanSoNgayConHang.Condition = FormatConditionEnum.Between;
                _StyleConditionGioiHanSoNgayConHang.Value1 = -10000;
                _StyleConditionGioiHanSoNgayConHang.Value2 = Convert.ToInt32(txtGioiHanTren.Text)+ 0.5;
                _StyleConditionGioiHanSoNgayConHang.ApplyToRow = true;
                gridViewMain.FormatConditions.Add(_StyleConditionGioiHanSoNgayConHang);
            }
            catch (Exception ex)
            {
            }

            try
            {
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsVatTuHangHoa.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                }
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewMain.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                }
                //foreach (DataRow row in dsHanSuDung.VatTuHangHoa.Rows)
                //{
                //    row["Choose"] = false;
                //}
                chkChooseAllVatTuHangHoa.Checked = false;
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
                FormatNumberInGridView(gridViewMain);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllVatTuHangHoa_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsHanSuDung.VatTuHangHoa.Rows)
            {
                row["Choose"] = chkChooseAllVatTuHangHoa.Checked;
            }
        }

        private void cmbNhomVatTuHangHoa_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbNhomVatTuHangHoa.EditValue = Guid.Empty;
        }
        private void cmbNhomVatTuHangHoa_EditValueChanged(object sender, EventArgs e)
        {
            //if (!(cmbNhomVatTuHangHoa.EditValue is Guid) || (Guid)cmbNhomVatTuHangHoa.EditValue == Guid.Empty) return;
            try
            {
                if (cmbNhomVatTuHangHoa.EditValue is Guid && (Guid)cmbNhomVatTuHangHoa.EditValue != Guid.Empty)
                {
                    //Dieu kien loc la ID = cmbNhomVatTuHangHoa.EditValue + ID cac nhom con.
                    string filterNhomCon = "CONVERT('{" + cmbNhomVatTuHangHoa.EditValue.ToString() + "}','System.Guid'), ";
                    DanhMucNhomVatTuHangHoa cacNhomCon = DanhMucNhomVatTuHangHoa.Instance.GetNhomVatTuHangHoaCon((Guid)cmbNhomVatTuHangHoa.EditValue);
                    foreach (NhomVatTuHangHoa nhomCon in cacNhomCon)
                    {
                        filterNhomCon += "CONVERT('{" + nhomCon.ID + "}','System.Guid'), ";
                        //filterNhomCon += string.Format(", '{0}'", nhomCon.ID);
                    }
                    if (filterNhomCon.EndsWith(", ")) filterNhomCon = filterNhomCon.Remove(filterNhomCon.Length - 2);

                    dsHanSuDung.VatTuHangHoa.Clear();
                    string filter = string.Format("NhomVatTuHangHoaID IN ({0}) AND TrangThai = 1 ", filterNhomCon);
                    dsHanSuDung.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.Filter(filter).DataView.ToTable());
                }
                else
                {
                    dsHanSuDung.VatTuHangHoa.Clear();
                    dsHanSuDung.VatTuHangHoa.Merge(DanhMucVatTuHangHoa.GetDanhMucHangHoaDangSuDung().DataView.ToTable());
                }
                chkChooseAllVatTuHangHoa.Checked = false;
                chkChooseAllVatTuHangHoa.Checked = true;
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private DataTable GetHangDaCoGiaoDich(SqlCommand cmd, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                
                cmd.CommandText = string.Format("SELECT DISTINCT A.VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                                "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID \n" +
                                                "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                "	AND A.VatTuHangHoaID is NOT NULL \n" +
                                                "UNION \n" +
                                                "SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID  \n" +
                                                "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                "WHERE SoLuong <> 0 \n" +
                                                "	AND A.VatTuHangHoaID is NOT NULL ");

                cmd.Parameters.Clear();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);

                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }

        private DataTable GetToanBoHangDangSuDung(SqlCommand cmd, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);

                cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                                "FROM NhatKyKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID \n" +
                                                "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                "	AND A.VatTuHangHoaID is NOT NULL \n" +
                                                "UNION \n" +
                                                "SELECT DISTINCT VatTuHangHoaID, B.NhomVatTuHangHoaID \n" +
                                                "FROM TonKho A INNER JOIN VatTuHangHoa B ON B.ID = A.VatTuHangHoaID  \n" +
                                                "WHERE SoLuong <> 0 \n" +
                                                "	AND A.VatTuHangHoaID is NOT NULL ");

                cmd.Parameters.Clear();
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }
            
        private void btnLoad_Click(object sender, EventArgs e)
        {
            //DateTime ngayBatDau = new DateTime(); if (LocalSettings.HeThong.CheDoBiKiemTra) ngayBatDau = DateTime.Now.AddDays(-2); else ngayBatDau = dtNgayBatDau.DateTime; 
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if(!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(ngayKetThuc);

            //int soNgayCanhBao = Convert.ToInt32(txtGioiHanTren.Text);

            BasicForms.FrmProgressBarDev.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandTimeout = GeneralLibs.Config.TimeOut;

                string vatTuHangHoaCondition ="";
                if (chkChooseAllVatTuHangHoa.Checked)
                {
                    if (cmbNhomVatTuHangHoa.Text == "")
                        vatTuHangHoaCondition = "1=1";
                    else
                        vatTuHangHoaCondition = string.Format("NhomVatTuHangHoaID = '{0}'", cmbNhomVatTuHangHoa.EditValue);
                }
                else
                {
                    if (chkShowHangDaCoGiaoDich.Checked) //Nếu lọc thuốc đã giao dịch thì để VatTuHangHoaID
                        vatTuHangHoaCondition = "VatTuHangHoaID IN (";
                    else //Nếu load tất thuốc từ danh mục thì cột VatTuHangHoaID chuyển thành ID
                        vatTuHangHoaCondition = "ID IN (";
                    foreach (DataRow row in dsHanSuDung.VatTuHangHoa.Rows)
                    {
                        if (row["Choose"] is bool && (bool)row["Choose"])
                        {
                            vatTuHangHoaCondition += string.Format("CONVERT('{0}', System.Guid), ", (Guid)row["ID"]);
                        }
                    }
                    if (vatTuHangHoaCondition.EndsWith(", "))
                        vatTuHangHoaCondition = vatTuHangHoaCondition.Substring(0, vatTuHangHoaCondition.Length - 2) + ")";
                    else vatTuHangHoaCondition = "1 = 0";
                }
                
                DataTable dtDaCoGiaoDich = new DataTable();
                //Nếu option chỉ chon những thuốc đã giao dịch thì chỉ get những thuốc đã có giao dịch
                if (chkShowHangDaCoGiaoDich.Checked)
                    dtDaCoGiaoDich = GetHangDaCoGiaoDich(cmd, ngayKetThuc);
                else //Nếu không thì lấy toàn bộ danh mục
                    dtDaCoGiaoDich = DanhMucVatTuHangHoa.Instance.DataTable;

                dtDaCoGiaoDich.DefaultView.RowFilter = vatTuHangHoaCondition;
                dtDaCoGiaoDich = dtDaCoGiaoDich.DefaultView.ToTable();
                dsHanSuDung.HanSuDungDetail.Clear();
                int count = 0;

                foreach (DataRow row in dtDaCoGiaoDich.Rows)
                {
                    BasicForms.FrmProgressBarDev.Status = string.Format("Đang xử lý {0}/{1}", count, dtDaCoGiaoDich.Rows.Count);
                    count++;

                    Guid vatTuHangHoaID;
                    if (chkShowHangDaCoGiaoDich.Checked) 
                        vatTuHangHoaID = (Guid)row["VatTuHangHoaID"];
                    else
                        vatTuHangHoaID = (Guid)row["ID"];

                    VatTuHangHoa vthh = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                    Lists.HanSuDung hsd = Lists.DanhMucHanSuDung.Instance.GetByVatTuHangHoaID(vatTuHangHoaID);
                    if (hsd != null)
                    {
                        DataRow rowAdd = dsHanSuDung.HanSuDungDetail.NewRow();
                        rowAdd["Ma"] = vthh.Ma;
                        rowAdd["Ten"] = vthh.Ten;
                        rowAdd["GiaBanLe"] = vthh.GiaBia;
                        rowAdd["SoLuongTon"] = hsd.SoLuongTon;
                        if (hsd.SoLuongTon > 0)
                        {
                            if (hsd.DateExpire is DateTime)
                                rowAdd["DateExpire"] = hsd.DateExpire;
                            rowAdd["SoChungTu"] = hsd.SoChungTu;
                            rowAdd["SoLo"] = hsd.SoLo;
                            if (hsd.NgayChungTu is DateTime)
                                rowAdd["NgayChungTu"] = hsd.NgayChungTu;
                            if (hsd.DateExpire is DateTime)
                            {
                                TimeSpan timeSpan = (TimeSpan)(DateTime.Now - hsd.DateExpire);
                                    rowAdd["NgayConLai"] = -timeSpan.Days;
                            }
                            rowAdd["SoLuongNhap"] = hsd.SoLuongNhap;
                        }
                        dsHanSuDung.HanSuDungDetail.Rows.Add(rowAdd);
                    }
                }

                FormatNumberInGridView(gridViewMain);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                FormatNumberInGridView(gridViewDsVatTuHangHoa);
                con.Close();
                con = null;
            }
            BasicForms.FrmProgressBarDev.FinishShowProgress();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeaderAndFooter(false, gridcontrolMain, true, true, "Thống kê chi tiết nhập xuất tồn", "", "", "", "");
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void txtGioiHanTren_EditValueChanged(object sender, EventArgs e)
        {
            if (txtGioiHanTren.Text != "")
                _StyleConditionGioiHanSoNgayConHang.Value2 = Convert.ToInt32(txtGioiHanTren.Text) + 0.5;
            else
            {
                _StyleConditionGioiHanSoNgayConHang.Value2 = 0;

            }
        }
    }
}
